package com.hdjk.view.activity.personalcenter;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hdjk.view.R;
import com.hdjk.view.callback.CallBackListener;
import com.hdjk.view.callback.ListDialogCallBackListener;
import com.hdjk.view.config.Constant;
import com.hdjk.view.dialog.EditTextPwdDialog;
import com.hdjk.view.dialog.MyAlertDialog;
import com.hdjk.view.dialog.TextButtonDialog;
import com.hdjk.view.entity.BankEntity;
import com.hdjk.view.entity.BuyFeeAndChargeEntity;
import com.hdjk.view.entity.BuyPlanEntity;
import com.hdjk.view.entity.FundEntity;
import com.hdjk.view.entity.IfastUserEntity;
import com.hdjk.view.entity.PayMethodEntity;
import com.hdjk.view.network.FundNetWork;
import com.hdjk.view.network.Network;
import com.hdjk.view.network.PersonalNetWork;
import com.hdjk.view.network.PlanNetWork;
import com.hdjk.view.network.TransactionNetWork;
import com.hdjk.view.util.SharedPreferencesUtil;
import com.hdjk.view.util.ToastUtils;
import com.hdjk.view.util.UserTokenUtil;
import com.lst.projectlib.base.BaseActivity;
import com.lst.projectlib.entity.BaseEntity;
import com.lst.projectlib.entity.Msg;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import static com.hdjk.view.R.id.tv_sure;

/**
 * 修改定投页面
 * Created by sxy on 2017/11/3.
 */

public class PlanFundModifyActivity extends BaseActivity implements View.OnClickListener {

    private int riskConfirmed = 0;
    private FundEntity mFund;
    private BuyPlanEntity mBuyPlan;
    private Handler mHandler = new Handler();
    private PayMethodEntity mPayMethod;
    private TextButtonDialog dialog;
    private MyAlertDialog alertDialog;
    private List<BankEntity> bankList;
    private ArrayList<BaseEntity> cycleList, dayList, weekList, groupList;
    private int bankIndex = 0;
    private int payMethod = 0;

    // Content View Elements
    private com.lst.projectlib.component.CustomView.TopTitleBar ttb_title_bar;
    private RelativeLayout rel_bank;
    private ImageView iv_bank_logo;
    private TextView tv_bank_name;
    private TextView tv_number;
    private TextView tv_rule;
    private TextView tv_wh;
    private EditText et_name;
    private com.hdjk.view.dialog.ListDialog ld_cycle;
    private com.hdjk.view.dialog.ListDialog ld_date;
    private RadioButton rbtn_yes;
    private RadioButton rbtn_no;
    private com.hdjk.view.dialog.ListDialog ld_group;
    private TextView tv_currency;
    private TextView tv_fund_code;
    private TextView tv_risk;
    private TextView tv_money_size;
    private EditText et_money;
    private TextView tv_rate;
    private TextView tv_cost;
    private TextView tv_buy;
    private TextView tv_yifeng;
    // End Of Content View Elements

    private void bindViews() {

        ttb_title_bar = (com.lst.projectlib.component.CustomView.TopTitleBar) findViewById(R.id.ttb_title_bar);
        rel_bank = (RelativeLayout) findViewById(R.id.rel_bank);
        iv_bank_logo = (ImageView) findViewById(R.id.iv_bank_logo);
        tv_bank_name = (TextView) findViewById(R.id.tv_bank_name);
        tv_number = (TextView) findViewById(R.id.tv_number);
        tv_rule = (TextView) findViewById(R.id.tv_rule);
        tv_wh = (TextView) findViewById(R.id.tv_wh);
        et_name = (EditText) findViewById(R.id.et_name);
        ld_cycle = (com.hdjk.view.dialog.ListDialog) findViewById(R.id.ld_cycle);
        ld_date = (com.hdjk.view.dialog.ListDialog) findViewById(R.id.ld_date);
        rbtn_yes = (RadioButton) findViewById(R.id.rbtn_yes);
        rbtn_no = (RadioButton) findViewById(R.id.rbtn_no);
        ld_group = (com.hdjk.view.dialog.ListDialog) findViewById(R.id.ld_group);
        tv_currency = (TextView) findViewById(R.id.tv_currency);
        tv_fund_code = (TextView) findViewById(R.id.tv_fund_code);
        tv_risk = (TextView) findViewById(R.id.tv_risk);
        tv_money_size = (TextView) findViewById(R.id.tv_money_size);
        et_money = (EditText) findViewById(R.id.et_money);
        tv_rate = (TextView) findViewById(R.id.tv_rate);
        tv_cost = (TextView) findViewById(R.id.tv_cost);
        tv_buy = (TextView) findViewById(R.id.tv_buy);
        tv_yifeng = (TextView) findViewById(R.id.tv_yifeng);
    }


    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_plan_buy);
        bindViews();
        ttb_title_bar.findViewById(R.id.tvNavBack).setOnClickListener(this);
        rel_bank.setOnClickListener(this);
        tv_buy.setOnClickListener(this);
        tv_yifeng.setOnClickListener(this);
        tv_rule.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        cycleList = new ArrayList<>();
        BaseEntity entity1 = new BaseEntity();
        entity1.setName("每月");
        cycleList.add(entity1);
        BaseEntity entity2 = new BaseEntity();
        entity2.setName("每两周");
        cycleList.add(entity2);
        BaseEntity entity3 = new BaseEntity();
        entity3.setName("每周");
        cycleList.add(entity3);
        BaseEntity entity4 = new BaseEntity();
        entity4.setName("每季");
        cycleList.add(entity4);
        ld_cycle.initData("请选择定投周期", cycleList, new ListDialogCallBackListener() {
            @Override
            public void OnChange(int index) {
                if (index == 0 || index == 3) {
                    ld_date.initData("请选择定投日期", dayList, new ListDialogCallBackListener() {
                        @Override
                        public void OnChange(int index) {

                        }
                    });
                } else {
                    ld_date.initData("请选择定投日期", weekList, new ListDialogCallBackListener() {
                        @Override
                        public void OnChange(int index) {

                        }
                    });
                }
            }
        });
        dayList = new ArrayList<>();
        for (int i = 1; i < 29; i++) {
            BaseEntity entity = new BaseEntity();
            entity.setName(i + "日");
            dayList.add(entity);
        }
        weekList = new ArrayList<>();
        for (int i = 1; i < 6; i++) {
            BaseEntity entity = new BaseEntity();
            switch (i) {
                case 1:
                    entity.setName("星期一");
                    break;
                case 2:
                    entity.setName("星期二");
                    break;
                case 3:
                    entity.setName("星期三");
                    break;
                case 4:
                    entity.setName("星期四");
                    break;
                case 5:
                    entity.setName("星期五");
                    break;
            }
            weekList.add(entity);
        }
        ld_date.initData("请选择定投日期", new ArrayList<BaseEntity>(), new ListDialogCallBackListener() {
            @Override
            public void OnChange(int index) {

            }
        });
        ArrayList<BaseEntity> group = new ArrayList<>();
        BaseEntity entity = new BaseEntity();
        entity.setName("个别投资组合");
        group.add(entity);
        ld_group.initData("个别投资组合", group, new ListDialogCallBackListener() {
            @Override
            public void OnChange(int index) {

            }
        });
        mBuyPlan = (BuyPlanEntity) getIntent().getExtras().getSerializable("entity");
        if (mBuyPlan != null) {
            ld_cycle.initTitle(mBuyPlan.getCycleName());
            if (mBuyPlan.getCycle().equals("weekly") || mBuyPlan.getCycle().equals("biweekly")) {
                ld_date.initData(mBuyPlan.getCycleDayName(), weekList, new ListDialogCallBackListener() {
                    @Override
                    public void OnChange(int index) {

                    }
                });
            } else {
                ld_date.initData(mBuyPlan.getCycleDayName(), dayList, new ListDialogCallBackListener() {
                    @Override
                    public void OnChange(int index) {

                    }
                });
            }
            et_name.setText(mBuyPlan.getName());
            et_money.setText(mBuyPlan.getSum());
//            setBankLogo(mBuyPlan.getInvestorPayBankCode());
//            if (mBuyPlan.getInvestorPayBankAccountNumber().length() > 4) {
//                tv_number.setText("(" + mBuyPlan.getInvestorPayBankAccountNumber().substring(mBuyPlan.getInvestorPayBankAccountNumber().length() - 4) + ")");
//            } else {
//                tv_number.setText("(" + mBuyPlan.getInvestorPayBankAccountNumber() + ")");
//            }
//            tv_bank_name.setText(mBuyPlan.getInvestorPayBankName());
            if (mBuyPlan.getPostponeDeduction().equals("1")) {
                rbtn_yes.setChecked(true);
            } else {
                rbtn_no.setChecked(true);
            }
            getFundDetail();
            getPayMethod();
        }
//        if (getIntent().getExtras().getSerializable("fund") instanceof FundEntity) {
//            mFund = (FundEntity) getIntent().getExtras().getSerializable("fund");
//            tv_currency.setText(mFund.getFundName());
//            tv_fund_code.setText(mFund.getFundCode());
//            tv_risk.setText(mFund.getRiskRateName());
//            if (!TextUtils.isEmpty(mFund.getFundStatus())) {
//                if ("0".equals(mFund.getFundStatus())) {
//                    tv_money_size.setText("（" + mFund.getMinInitialIpoAmount() + "---" + mFund.getMaxIpoAmount() + "）");
//                } else if ("1".equals(mFund.getFundStatus())) {
//                    tv_money_size.setText("（" + mFund.getMinInitialBuyAmount() + "---" + mFund.getMaxBuyAmount() + "）");
//                }
//            }
//        }

        et_money.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (delayRun != null) {
                    //每次editText有变化的时候，则移除上次发出的延迟线程
                    mHandler.removeCallbacks(delayRun);
                }
                //延迟1000ms，如果不再输入字符，则执行该线程的run方法
                mHandler.postDelayed(delayRun, 1000);
            }
        });
    }

    private void getPayMethod() {
        mDialog.show();
        JSONObject object = new JSONObject();
        try {
            object.put("accountNumber", UserTokenUtil.getUserName(PlanFundModifyActivity.this));
            TransactionNetWork.getPayMethod(UserTokenUtil.getToken(PlanFundModifyActivity.this), object.toString(), new CallBackListener() {
                @Override
                public void onCallBackCompleted(Msg msg) {
                    mDialog.cancel();
                    if (msg != null && msg.getSuccess() && msg.getData() != null && msg.getData() instanceof PayMethodEntity) {
                        mPayMethod = (PayMethodEntity) msg.getData();
                        setPayMethod(0,mBuyPlan.getInvestorPayId()+"");
//                        if (mPayMethod.getInvestorBankDetails() != null && mPayMethod.getInvestorBankDetails().getData() != null && mPayMethod.getInvestorBankDetails().getData().size() > 0) {
//                            for (int i = 0; i < mPayMethod.getInvestorBankDetails().getData().size(); i++) {
//                                if (mPayMethod.getInvestorBankDetails().getData().get(i).getPreferred().equals("Y")) {
//                                    setPayMethod(payMethod, mPayMethod.getInvestorBankDetails().getData().get(i).getInvestorPayId());
//                                }
//                            }
//                        }
                    }
                }

                @Override
                public void onCallBackError(Msg msg) {
                    mDialog.cancel();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void setPayMethod(int type, String investorPayId) {
        if (mPayMethod != null) {
            if (type == 0) {//银行卡
                if (mPayMethod.getInvestorBankDetails() != null && mPayMethod.getInvestorBankDetails().getData() != null && !TextUtils.isEmpty(investorPayId)) {
                    for (int i = 0; i < mPayMethod.getInvestorBankDetails().getData().size(); i++) {
                        if (investorPayId.equals(mPayMethod.getInvestorBankDetails().getData().get(i).getInvestorPayId()))
                            bankIndex = i;
                    }
                    switch (mPayMethod.getInvestorBankDetails().getData().get(bankIndex).getBankCode()) {
                        case "GDB":
                            iv_bank_logo.setImageDrawable(PlanFundModifyActivity.this.getResources().getDrawable(R.drawable.icon_gdb));
                            break;
                        case "ABC":
                            iv_bank_logo.setImageDrawable(PlanFundModifyActivity.this.getResources().getDrawable(R.drawable.icon_abc));
                            break;
                        case "ICBC":
                            iv_bank_logo.setImageDrawable(PlanFundModifyActivity.this.getResources().getDrawable(R.drawable.icon_icbc));
                            break;
                        case "CMBC":
                            iv_bank_logo.setImageDrawable(PlanFundModifyActivity.this.getResources().getDrawable(R.drawable.icon_cmbc));
                            break;
                        case "CEB":
                            iv_bank_logo.setImageDrawable(PlanFundModifyActivity.this.getResources().getDrawable(R.drawable.icon_ceb));
                            break;
                        case "HXBANK":
                            iv_bank_logo.setImageDrawable(PlanFundModifyActivity.this.getResources().getDrawable(R.drawable.icon_hxbank));
                            break;
                        case "SPABANK":
                            iv_bank_logo.setImageDrawable(PlanFundModifyActivity.this.getResources().getDrawable(R.drawable.icon_spabank));
                            break;
                        case "CIB":
                            iv_bank_logo.setImageDrawable(PlanFundModifyActivity.this.getResources().getDrawable(R.drawable.icon_cib));
                            break;
                        case "SPDB":
                            iv_bank_logo.setImageDrawable(PlanFundModifyActivity.this.getResources().getDrawable(R.drawable.icon_spdb));
                            break;
                        case "CITIC":
                            iv_bank_logo.setImageDrawable(PlanFundModifyActivity.this.getResources().getDrawable(R.drawable.icon_citic));
                            break;
                        case "COMM":
                            iv_bank_logo.setImageDrawable(PlanFundModifyActivity.this.getResources().getDrawable(R.drawable.icon_comm));
                            break;
                        case "CMB":
                            iv_bank_logo.setImageDrawable(PlanFundModifyActivity.this.getResources().getDrawable(R.drawable.icon_cmb));
                            break;
                        case "CCB":
                            iv_bank_logo.setImageDrawable(PlanFundModifyActivity.this.getResources().getDrawable(R.drawable.icon_ccb));
                            break;
                        case "BOC":
                            iv_bank_logo.setImageDrawable(PlanFundModifyActivity.this.getResources().getDrawable(R.drawable.icon_boc));
                            break;
                        case "PSBC":
                            iv_bank_logo.setImageDrawable(PlanFundModifyActivity.this.getResources().getDrawable(R.drawable.icon_psbc));
                            break;
                    }
                    String number = mPayMethod.getInvestorBankDetails().getData().get(bankIndex).getBankNumber();
                    if (!TextUtils.isEmpty(number)) {
                        if (number.length() > 4) {
                            tv_number.setText("(" + number.substring(number.length() - 4) + ")");
                        } else {
                            tv_number.setText("(" + number + ")");
                        }
                    }
                    bankList = SharedPreferencesUtil.getBankList(PlanFundModifyActivity.this);
                    if (bankList == null || bankList.size() == 0) {
                        Network.getBankList(UserTokenUtil.getToken(PlanFundModifyActivity.this), new CallBackListener() {
                            @Override
                            public void onCallBackCompleted(Msg msg) {
                                if (msg != null) {
                                    if (msg.getSuccess()) {
                                        if (!TextUtils.isEmpty(msg.getResult()))
                                            SharedPreferencesUtil.saveBankList(PlanFundModifyActivity.this, msg.getResult());
                                        bankList = (List<BankEntity>) msg.getData();
                                        for (int i = 0; i < bankList.size(); i++) {
                                            if (bankList.get(i).getBankCode().equals(mPayMethod.getInvestorBankDetails().getData().get(bankIndex).getBankCode())) {
                                                tv_bank_name.setText(bankList.get(i).getName());
                                                break;
                                            }
                                        }
                                    }
                                }
                            }

                            @Override
                            public void onCallBackError(Msg msg) {
                                mDialog.cancel();
                            }
                        });
                    } else {
                        for (int i = 0; i < bankList.size(); i++) {
                            if (bankList.get(i).getBankCode().equals(mPayMethod.getInvestorBankDetails().getData().get(bankIndex).getBankCode())) {
                                tv_bank_name.setText(bankList.get(i).getName());
                                break;
                            }
                        }
                    }
                    tv_number.setVisibility(View.VISIBLE);
                    tv_wh.setVisibility(View.VISIBLE);
                }
            } else if (type == 1) {//现金钱包
                if (mPayMethod.getInvestorCashWallets() != null && mPayMethod.getInvestorCashWallets().getData() != null) {
                    iv_bank_logo.setImageDrawable(getResources().getDrawable(R.drawable.wallet));
                    tv_bank_name.setText("现金钱包");
                    tv_number.setVisibility(View.GONE);
                    tv_wh.setVisibility(View.GONE);
                }
            }
        }
    }

    private void getFundDetail() {
        mDialog.show();
        JSONObject object = new JSONObject();
        try {
            object.put("fundCode", mBuyPlan.getProducts().get(0).getFundCode());
            FundNetWork.getFundDetail(UserTokenUtil.getToken(PlanFundModifyActivity.this), object.toString(), new CallBackListener() {
                @Override
                public void onCallBackCompleted(Msg msg) {
                    mDialog.dismiss();
                    if (msg != null && msg.getSuccess() && msg.getData() != null) {
                        mFund = (FundEntity) msg.getData();
                        tv_currency.setText(mFund.getFundName());
                        tv_fund_code.setText(mFund.getFundCode());
                        tv_risk.setText(mFund.getRiskRateName());
                        if (!TextUtils.isEmpty(mFund.getFundStatus())) {
                            if ("0".equals(mFund.getFundStatus())) {
                                tv_money_size.setText("（" + mFund.getMinInitialIpoAmount() + "---" + mFund.getMaxIpoAmount() + "）");
                            } else if ("1".equals(mFund.getFundStatus())) {
                                tv_money_size.setText("（" + mFund.getMinInitialBuyAmount() + "---" + mFund.getMaxBuyAmount() + "）");
                            }
                        }
                    }
                }

                @Override
                public void onCallBackError(Msg msg) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 延迟线程，看是否还有下一个字符输入
     */
    private Runnable delayRun = new Runnable() {

        @Override
        public void run() {
            //在这里调用服务器的接口，获取数据
            getPayFeeAndCharge();
        }
    };

    private void getPayFeeAndCharge() {
        if (!TextUtils.isEmpty(et_money.getText().toString())) {
            int money = Integer.parseInt(et_money.getText().toString());
            if (money > 0) {
                JSONObject object = new JSONObject();
                try {
                    object.put("fundCode", mFund.getFundCode());
                    object.put("investmentAmount", money);
                    TransactionNetWork.getBuyFeeAndCharge(UserTokenUtil.getToken(PlanFundModifyActivity.this), object.toString(), new CallBackListener() {
                        @Override
                        public void onCallBackCompleted(Msg msg) {
                            if (msg != null && msg.getSuccess() && msg.getData() != null && msg.getData() instanceof BuyFeeAndChargeEntity) {
                                BuyFeeAndChargeEntity entity = (BuyFeeAndChargeEntity) msg.getData();
                                tv_rate.setText(entity.getSalesChargesRate() + "%");
                                tv_cost.setText(entity.getSalesCharges());
                            }
                        }

                        @Override
                        public void onCallBackError(Msg msg) {

                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        } else {
            tv_rate.setText("0.00%");
            tv_cost.setText("0.00");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvNavBack:
                back();
                break;
            case R.id.tv_yifeng:
                showPopupWindow(tv_yifeng);
                break;
            case R.id.rel_bank:
                Intent intent = new Intent(this, SelectPaymentActivity.class);
                intent.putExtra("isWallet", true);
                startActivityForResult(intent, 61);
                break;
            case R.id.tv_rule:
                View view = LayoutInflater.from(this).inflate(R.layout.layout_rule_dialog, null);
                AlertDialog dialog = new AlertDialog.Builder(this).setView(view).create();
                dialog.show();
                break;
            case R.id.tv_buy:
                buy();
                break;
        }
    }

    private String getCycle() {
        String s = "";
        switch (ld_cycle.getItem()) {
            case 0://每月
                s = "monthly";
                break;
            case 1://每两周
                s = "biweekly";
                break;
            case 2://每周
                s = "weekly";
                break;
            case 3://每季
                s = "quarterly";
                break;
        }
        return s;
    }

    private void buy() {
        String cycle = ld_cycle.getItem() >= 0 ? getCycle() : mBuyPlan.getCycle();
        int date = ld_date.getItem() >= 0 ? ld_date.getItem() + 1 : mBuyPlan.getCycleDay();
        String money = et_money.getText().toString();
        if (TextUtils.isEmpty(cycle)) {
            ToastUtils.showShortToast(PlanFundModifyActivity.this, "请选择定投周期");
            return;
        }
        if (date == 0) {
            ToastUtils.showShortToast(PlanFundModifyActivity.this, "请选择定投日期");
            return;
        }
        if (TextUtils.isEmpty(money)) {
            ToastUtils.showShortToast(PlanFundModifyActivity.this, "请输入购买金额");
            return;
        }
        if ("0".equals(mFund.getFundStatus())) {
            if (Double.parseDouble(money) < Double.parseDouble(mFund.getMinInitialIpoAmount())) {
                ToastUtils.showShortToast(this, "购买金额低于最低限制");
                return;
            }
            if (Double.parseDouble(money) > Double.parseDouble(mFund.getMaxIpoAmount())) {
                ToastUtils.showShortToast(this, "购买金额高于最高限制");
                return;
            }
        } else if ("1".equals(mFund.getFundStatus())) {
            if (Double.parseDouble(money) < Double.parseDouble(mFund.getMinInitialBuyAmount())) {
                ToastUtils.showShortToast(this, "购买金额低于最低限制");
                return;
            }
            if (Double.parseDouble(money) > Double.parseDouble(mFund.getMaxBuyAmount())) {
                ToastUtils.showShortToast(this, "购买金额高于最高限制");
                return;
            }
        }
        mDialog.show();
        JSONObject obj = new JSONObject();
        try {
            obj.put("accountNumber", UserTokenUtil.getUserName(PlanFundModifyActivity.this));
            PersonalNetWork.getIfastUserInfo(UserTokenUtil.getToken(PlanFundModifyActivity.this), obj.toString(), new CallBackListener() {
                @Override
                public void onCallBackCompleted(Msg msg) {
                    mDialog.cancel();
                    if (msg != null && msg.getSuccess() && msg.getData() != null && msg.getData() instanceof IfastUserEntity) {
                        IfastUserEntity userEntity = (IfastUserEntity) msg.getData();
                        if (Integer.parseInt(userEntity.getRiskAppetite()) < 1) {
                            Intent intent = new Intent(PlanFundModifyActivity.this, RiskTestListActivity.class);
                            startActivity(intent);
                            ToastUtils.showShortToast(PlanFundModifyActivity.this, "您未进行风险能力测试，请先测试");
                            return;
                        }
                        if (Integer.parseInt(userEntity.getRiskAppetite()) == 1 && Integer.parseInt(mFund.getRiskRate()) > 1) {
                            ToastUtils.showShortToast(PlanFundModifyActivity.this, "您的风险等级为保守型，不能购买超过风险等级的产品");
                            return;
                        }
                        if (Integer.parseInt(mFund.getRiskRate()) > Integer.parseInt(userEntity.getRiskAppetite())) {
                            dialog = new TextButtonDialog(PlanFundModifyActivity.this, R.style.progress_dialog, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    switch (v.getId()) {
                                        case R.id.tv_cancel:
                                            dialog.dismiss();
                                            break;
                                        case tv_sure:
                                            dialog.dismiss();
                                            riskConfirmed = 1;
                                            showPwdDialog();
                                            break;
                                    }
                                }
                            });
                            dialog.setDialogContent("此基金的购买风险超出您的风险承受能力，确定要购买吗？", 15);
                            dialog.show();
                        } else {
                            showPwdDialog();
                        }
                    }
                }

                @Override
                public void onCallBackError(Msg msg) {
                    mDialog.cancel();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private void showPwdDialog() {
        EditTextPwdDialog dialog = new EditTextPwdDialog(this, "输入密码", "", getResources().getDrawable(R.drawable.icon_input_pwd), "请输入交易密码", new EditTextPwdDialog.OnSureClickListener() {
            @Override
            public void onSureClick(String txt) {
                mDialog.show();
                JSONObject object = new JSONObject();
                try {
                    object.put("accountNumber", UserTokenUtil.getUserName(PlanFundModifyActivity.this));
                    object.put("cycle", ld_cycle.getItem() >= 0 ? getCycle() : mBuyPlan.getCycle());
                    object.put("cycleDay", ld_date.getItem() >= 0 ? ld_date.getItem() + 1 : mBuyPlan.getCycleDay());
                    object.put("investorPayId", mBuyPlan.getInvestorPayId());
                    object.put("password", txt);
                    object.put("postponeDeduction", rbtn_yes.isChecked() ? 1 : 0);
                    JSONArray array = new JSONArray();
                    JSONObject obj = new JSONObject();
                    obj.put("currency", "156");
                    obj.put("fundCode", mFund.getFundCode());
                    obj.put("rspAmount", et_money.getText().toString());
                    array.put(obj);
                    object.put("products", array);
                    object.put("riskConfirmed", riskConfirmed);
                    object.put("rspId", mBuyPlan.getRspId());
                    Calendar calendar = Calendar.getInstance();
                    int year = calendar.get(Calendar.YEAR);
                    int month = calendar.get(Calendar.MONTH) + 1;
                    int day = calendar.get(Calendar.DAY_OF_MONTH);
                    object.put("rspName", TextUtils.isEmpty(et_name.getText().toString()) ? "" + year + (month > 9 ? month : ("0" + month)) + (day > 9 ? day : ("0" + day)) : et_name.getText().toString());
                    PlanNetWork.modifyPlan(UserTokenUtil.getToken(PlanFundModifyActivity.this), object.toString(), new CallBackListener() {
                        @Override
                        public void onCallBackCompleted(Msg msg) {
                            mDialog.cancel();
                            String title = "";
                            if (msg != null && msg.getSuccess()) {
                                title = "修改成功";
                                Intent intent = new Intent(Constant.INTENT_FILTER_STRING_AFTER_BUY_PLAN_MODIFY_STATE);
                                sendBroadcast(intent);
                                setResult(333);
                                back();
                            } else {
                                if (TextUtils.isEmpty(msg.getMsg())) {
                                    title = "修改失败";
                                } else {
                                    title = msg.getMsg();
                                }
                            }
                            ToastUtils.showShortToast(PlanFundModifyActivity.this, title);
                        }

                        @Override
                        public void onCallBackError(Msg msg) {
                            mDialog.cancel();
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 61 && resultCode == 61) {
            String investorPayId = "";
            payMethod = data.getIntExtra("payMethod", -1);
            if (payMethod == 0) {
                investorPayId = data.getStringExtra("investorPayId");
            }
            if (payMethod >= 0) {
                setPayMethod(payMethod, investorPayId);
            }
        }
    }
}
